// lib\hooks.js
import {useEffect, useState} from "react";

export function useFormState(action) {
    const [state, setState] = useState({error: null, loading: false});

    const handleSubmit = async (event) => {
        event.preventDefault()
        setState({loading: true, error: null})
        const form = event.currentTarget
        const formData = new FormData(form)
        const result = await action(formData)
        if (result?.isError) {
            setState({loading: false, error: result})
        } else {
            // 重置表单, 清空内容
            form.reset()
            setState({loading: false, error: null})
        }
    }

    return [state, handleSubmit]
}

export function useIsClient() {
    // 解决水合时属性不一致报错
    const [isClient, setIsClient] = useState(false)
    useEffect(() => setIsClient(true), [])
    return isClient
}